package com.douya.mvc.utils;

import com.douya.common.pojo.vo.CommonMapVO;
import org.apache.commons.io.FileUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;

/**
 * 说明：文件输出工具类
 *
 * @Author 胡晨烨
 * @Date 2020/2/20
 */
public class DownLoadFileUtils {


    /**
     * 通过浏览器下载文件根据路径
     *
     * @param response 响应
     * @param fileName 文件名
     * @param filePath 文件路径
     * @param delete   是否删除
     * @return 是否成功
     */
    public static boolean download(HttpServletResponse response, String fileName, String filePath, boolean delete) {
        OutputStream os = null;
        try {
            File f = new File(filePath);
            os = response.getOutputStream();
            response.reset();
            response.setHeader("Content-Disposition",
                    "attachment" +
                            ";filename=" + urlEncode(fileName)
            );
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream; charset=utf-8");
            int length = Integer.parseInt(String.valueOf(f.length()));
            response.setContentLength(length);
            response.setContentType("UTF-8");
            os.write(FileUtils.readFileToByteArray(f));
            os.flush();
            if (delete) {
                FileUtils.deleteQuietly(f);
            }
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            try {
                if (os != null) {
                    os.flush();
                    os.close();
                }
            } catch (Exception ignored) {
            }
        }
    }

    /**
     * 文件流
     *
     * @param filePath 文件地址
     * @param fileName 文件名
     * @param response 响应
     * @param request  请求
     * @throws Exception 异常
     */
    public static void download(String filePath, String fileName, HttpServletResponse response, HttpServletRequest request) throws Exception {
        File file = new File(filePath);
        InputStream inputStream = Files.newInputStream(file.toPath());
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/" + fileName + ";charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;fileName=" + setFileDownloadHeader(request, fileName));

        byte[] b = new byte[1024];

        int length;
        while ((length = inputStream.read(b)) > 0) {
            response.getOutputStream().write(b, 0, length);
        }
    }

    /**
     * 设置文件名称
     *
     * @param request  请求
     * @param fileName 文件名
     * @return 文件名
     * @throws UnsupportedEncodingException 异常
     */
    public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
        String agent = request.getHeader("USER-AGENT");
        String filename;
        if (agent.contains("MSIE")) {
            filename = URLEncoder.encode(fileName, "utf-8");
            filename = filename.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            filename = new String(fileName.getBytes(), "ISO8859-1");
        } else if (agent.contains("Chrome")) {
            filename = URLEncoder.encode(fileName, "utf-8");
        } else {
            filename = URLEncoder.encode(fileName, "utf-8");
        }
        return filename;
    }

    /**
     * 获取文件流
     *
     * @param filePath     文件路径
     * @param realFileName 文件名
     * @return 文件流
     */
    public static CommonMapVO<String, byte[]> getFileFlow(String filePath, String realFileName) {
        File file = new File(filePath);
        if (file.exists() && file.length() > 0) {
            FileInputStream fis = null;
            byte[] buffer;
            ByteArrayOutputStream baos = null;
            try {
                fis = new FileInputStream(file);
                baos = new ByteArrayOutputStream(fis.available());
                byte[] bytes = new byte[fis.available()];
                int temp;
                while ((temp = fis.read(bytes)) > 0) {
                    baos.write(bytes, 0, temp);
                }
            } catch (Exception e) {
                return null;
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                } catch (IOException ignored) {
                }
                try {
                    if (baos != null) {
                        baos.close();
                    }
                } catch (IOException ignored) {
                }
            }
            buffer = baos.toByteArray();
            return new CommonMapVO<String, byte[]>()
                    .setKey(realFileName).setTitle(buffer);
        }
        return null;
    }

    /**
     * 通过浏览器下载文件根据字符流
     *
     * @param response 响应
     * @param fileName 文件名
     * @param bt       字符流
     * @param length   长度
     * @return 是否成功
     */
    public static boolean download(HttpServletResponse response, String fileName, byte[] bt, int length) {
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            response.reset();
            response.setHeader("Content-Disposition",
                    "attachment" +
                            ";filename=" + urlEncode(fileName)
            );
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setContentLength(length);
            response.setContentType("UTF-8");
            os.write(bt);
            os.flush();
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            try {
                if (os != null) {
                    os.flush();
                    os.close();
                }
            } catch (Exception ignored) {
            }
        }
    }

    /**
     * url编码
     *
     * @param param 部分
     * @return 编码
     */
    public static String urlEncode(String param) {
        try {
            return URLEncoder.encode(param, "UTF-8");
        } catch (Exception ignored) {
            return "";
        }
    }


}


